package pers.kevin.fsm.server;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TcpServer {
	
	public static void main(String[] args) {
		ServerSocket serverSocket = null;
		Socket socket = null;
		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			serverSocket = new ServerSocket(9000);
			socket = serverSocket.accept();
			reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
			String command = "";
			while(!(command = reader.readLine()).equals("quit")) {
			   //create CommandOperator 
			    CommandOperator operator = new CommandOperator(command);
			    //execute command
			    String result = operator.execute();
			    writer.write(result);
			    writer.newLine();
			    writer.flush();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			try {
				if(reader != null) {
				    reader.close();
				}
				if(writer != null){
				    writer.close();
				}
				if(socket != null) {
				    socket.close();
				}
				if(serverSocket != null) {
				    serverSocket.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

}
